// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV });
const db = cloud.database({
  throwOnNotFound: false
})
const _ = db.command
const $ = db.command.aggregate

async function updateUser(userid, updData) {
  updData.modified_time = new Date();
  return await db.collection('tb_user_info')
    .where({ _id: userid })
    .update({ data: updData })
}

async function searchUserList(searchText, searchData) {
  const res = await db.collection('tb_user_info').aggregate()
    .match(searchData)
    .match(
      _.or([
        { username: new RegExp(searchText, 'i') },
        { real_name: new RegExp(searchText, 'i') },
      ])
    )
    .lookup({
      from: 'tb_role_info',
      localField: 'role_id',
      foreignField: '_id',
      as: 'role'
    })
    .project({
      username: 1, real_name: 1, gender: 1, avatar: 1, phone: 1, role_id: 1, user_state: 1,
      role_name: $.arrayElemAt(['$role.role_name', 0]),
      created_time: 1, login_time: 1
    })
    .limit(200)
    .end();
  return res.list;
}

async function getProfile(user_id) {
  return await db.collection('tb_user_info').doc(user_id).get();
}

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext();
  const openid = wxContext.OPENID;
  if (event.funcName == 'query') {
    return await searchUserList(event.searchText, event.searchData);
  } else if (event.funcName == 'update') {
    return await updateUser(event.userid || openid, event.updData);
  } else if (event.funcName == 'getProfile') {
    return await getProfile(openid);
  }
  return {
    event,
  }
}